package org.jeecgframework.web.controller;

import org.jeecgframework.core.util.*;
import org.jeecgframework.web.service.*;
import org.jeecgframework.web.system.pojo.base.*;

import java.io.File;
import java.text.ParseException;
import java.util.*;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.web.util.FileBean;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;

import java.io.OutputStream;

import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.IOException;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 光管翻新完工单
 * @date 2018-03-17 14:26:28
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsLightReportController")
public class CbsLightReportController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsLightReportController.class);

    @Autowired
    private CbsLightReportServiceI cbsLightReportService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private CbsServiceLogServiceI cbsServiceLogServiceI;
    @Autowired
    private CbsServiceErrorLogServiceI cbsServiceErrorLogService;

    private String message;

    @Autowired
    CbsServiceReportServiceI cbsServiceReportService;
    @Autowired
    private CbsInspectionEvaluateServiceI cbsInspectionEvaluateService;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 光管翻新完工单列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsLightReport")
    public ModelAndView cbsLightReport(HttpServletRequest request) {
        return new ModelAndView("com/zybk/org.jeecgframework/cbsLightReportList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(CbsLightReportEntity cbsLightReport, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(CbsLightReportEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsLightReport, request.getParameterMap());
        try {
            //自定义追加查询条件
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.cbsLightReportService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 光管翻新完工单新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsLightReportEntity cbsLightReport, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsLightReport.getId())) {
            cbsLightReport = cbsLightReportService.getEntity(CbsLightReportEntity.class, cbsLightReport.getId());
            req.setAttribute("cbsLightReportPage", cbsLightReport);
        }
        return new ModelAndView("com/zybk/org.jeecgframework/cbsLightReport-add");
    }


    /**
     * 添加光管翻新完工单
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsLightReportEntity cbsLightReport, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "光管翻新完工单添加成功";
        try {
            cbsLightReportService.save(cbsLightReport);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "光管翻新完工单添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 光管翻新完工单编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsLightReportEntity cbsLightReport, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsLightReport.getId())) {
            cbsLightReport = cbsLightReportService.getEntity(CbsLightReportEntity.class, cbsLightReport.getId());
            req.setAttribute("cbsLightReportPage", cbsLightReport);
        }
        return new ModelAndView("com/zybk/org.jeecgframework/cbsLightReport-update");
    }

    /**
     * 更新光管翻新完工单
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsLightReportEntity cbsLightReport, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "光管翻新完工单更新成功";
        CbsLightReportEntity t = cbsLightReportService.get(CbsLightReportEntity.class, cbsLightReport.getId());
        try {
            MyBeanUtils.copyBeanNotNull2Bean(cbsLightReport, t);
            cbsLightReportService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "光管翻新完工单更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }


    /**
     * 删除光管翻新完工单
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsLightReportEntity cbsLightReport, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsLightReport = systemService.getEntity(CbsLightReportEntity.class, cbsLightReport.getId());
        message = "光管翻新完工单删除成功";
        try {
            cbsLightReportService.delete(cbsLightReport);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "光管翻新完工单删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除光管翻新完工单
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "光管翻新完工单删除成功";
        try {
            for (String id : ids.split(",")) {
                CbsLightReportEntity cbsLightReport = systemService.getEntity(CbsLightReportEntity.class,
                        id
                );
                cbsLightReportService.delete(cbsLightReport);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "光管翻新完工单删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView("com/zybk/org.jeecgframework/cbsLightReportUpload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(CbsLightReportEntity cbsLightReport, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        CriteriaQuery cq = new CriteriaQuery(CbsLightReportEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsLightReport, request.getParameterMap());
        List<CbsLightReportEntity> cbsLightReports = this.cbsLightReportService.getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "光管翻新完工单");
        modelMap.put(NormalExcelConstants.CLASS, CbsLightReportEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("光管翻新完工单列表", "导出人:" + ResourceUtil.getSessionUserName().getRealName(),
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, cbsLightReports);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsLightReportEntity cbsLightReport, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(TemplateExcelConstants.FILE_NAME, "光管翻新完工单");
        modelMap.put(TemplateExcelConstants.PARAMS, new TemplateExportParams("Excel模板地址"));
        modelMap.put(TemplateExcelConstants.MAP_DATA, null);
        modelMap.put(TemplateExcelConstants.CLASS, CbsLightReportEntity.class);
        modelMap.put(TemplateExcelConstants.LIST_DATA, null);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CbsLightReportEntity> listCbsLightReportEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(), CbsLightReportEntity.class, params);
                for (CbsLightReportEntity cbsLightReport : listCbsLightReportEntitys) {
                    cbsLightReportService.save(cbsLightReport);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }


    /**
     * 根据code值获取市
     */
    @RequestMapping(params = "getCityByCode")
    @ResponseBody
    public AjaxJson getCityByCode(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            String code = request.getParameter("province");
            String hql = "from TSTerritory where territoryLevel = 2 and TSTerritory.territoryCode = '" + code + "' ";
            List<TSTerritory> territoryList = systemService.findHql(hql);
            ajaxJson.setObj(territoryList);
        } catch (Exception e) {
            e.getMessage();
        }
        return ajaxJson;
    }


    /*
     * 光管翻新暂存
     * */
    @RequestMapping(params = "ZCLightReport")
    @ResponseBody
    public AjaxJson ZCLightReport(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            j = cbsLightReportService.ZCLightReport(request);
        } catch (Exception e) {
            j.setMsg("暂存失败");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

    /*
     * 光管翻新提交
     * */
    @RequestMapping(params = "subLightReport")
    @ResponseBody
    public AjaxJson subLightReport(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            j = cbsLightReportService.subLightReport(request);
        } catch (Exception e) {
            j.setMsg("提交失败");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }


    /**
     * 上传附件功能
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "fileUploadView")
    public AjaxJson fileUploadView(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        Map<String, Object> attributes = new HashMap<String, Object>();
        String cbsServiceId = oConvertUtils.getString(request.getParameter("serviceId"));
        String businessType = request.getParameter("businessType");
        if (cbsServiceId != null && cbsServiceId != "") {
            FileBean fileBean = UploadFileUtil.UploadFile(request);
            if (StringUtil.isNotEmpty(cbsServiceId)) {
                ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
                zyfileLog.setBusinessKey(cbsServiceId);
                zyfileLog.setFilePath(fileBean.getSavePath());
                zyfileLog.setOldFileName(fileBean.getFileRealName());
                zyfileLog.setNewFileName(fileBean.getFileName());
                zyfileLog.setCreateDate(new Date());
                zyfileLog.setCreateDate(new Date());
                zyfileLog.setBusinessType("I");
                zyfileLog.setBusinessChildType("IF");
                zyfileLog.setFileType("wgd");
                systemService.save(zyfileLog);
//
            }
            String id = null;
            Map<String, Object> fileLogMap = systemService.findOneForJdbc("SELECT t.id FROM zy_file_log t where  t.business_key = '" + cbsServiceId + "' and old_file_name = '" + fileBean.getFileRealName() + "'order by t.create_date desc limit 1 ");
            if (fileLogMap != null) {
                id = fileLogMap.get("id").toString();
            }
            attributes.put("name", fileBean.getFileRealName());
            attributes.put("id", id);
            try {
            } catch (Exception e) {
                e.printStackTrace();
            }
            j.setAttributes(attributes);
        }
        return j;
    }

    /**
     * 上传照片功能
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "photoFileUploadView")
    public AjaxJson photoFileUploadView(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String cbsServiceId = oConvertUtils.getString(request.getParameter("serviceId"));
        String businessType = request.getParameter("businessType");
        String photoName = request.getParameter("photoName");

        Map<String, Object> attributes = cbsLightReportService.photoFileUploadView(request, cbsServiceId, businessType, photoName);

        j.setAttributes(attributes);
        return j;
    }

    /**
     * 删除上传的文件
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "delFile")
    public AjaxJson delFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            String id = oConvertUtils.getString(request.getParameter("id"));
            if (id != null && id != "") {
                systemService.deleteEntityById(ZyFileLogEntity.class, id);
                j.setMsg("文件删除成功");
                j.setSuccess(true);
            }
        } catch (Exception e) {
            j.setMsg(e.getMessage());
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }


}
